package project.sample.io;

import project.sample.protocol.http.*;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Callable;

public class WorkerThread implements Callable {

    private Socket socket;

    public WorkerThread(Socket socket) {
        this.socket = socket;
    }

    @Override
    public Object call() throws Exception {
        if (socket == null) {
            return null;
        }
        InputStream in = socket.getInputStream();
        String first = readLine(in);
        String[] arr = first.split(" ");
        if (arr.length != 3) {
            throw new RuntimeException("http protocol parsed error");
        }
        String method = arr[0];
        String path = arr[1];
        String protocol = arr[2];
        List<HttpHeader> headers = new ArrayList<>();
        int contentLength = -1;
        while (true) {
            String line = readLine(in);
            if ("".equals(line)) {
                break;
            }
            String[] kv = line.split(": ");
            if (kv.length == 2) {
                if ("Content-Length".equalsIgnoreCase(kv[0])) {
                    contentLength = Integer.parseInt(kv[1]);
                }
                headers.add(new HttpHeader(kv[0], new String[]{kv[1]}));
            }
        }
        byte[] body = null;
        if (contentLength > -1) {
            body = new byte[contentLength];
            in.read(body);
        }
        HttpRequest request = new DefaultHttpRequest(headers, method, "http://localhost", path, protocol, "localhost", body);
        execute();
        response();
        in.close();
        socket.close();
        return null;
    }

    private void response() throws IOException {
        HttpResponse response = new DefaultHttpResponse(new ArrayList<>(Arrays.asList(new HttpHeader("Content-Type", new String[]{"text/html"}), new HttpHeader("Content-Length", new String[]{"2"}))), 200);
        response.body("ok".getBytes());
        OutputStream out = socket.getOutputStream();
        out.write(response.bytes());
        out.flush();
        out.close();
    }


    private void execute() {
    }

    private String readLine(InputStream in) throws IOException {
        StringBuilder line = new StringBuilder();
        while (true) {
            int b = in.read();
            if (b == '\n') {
                break;
            }
            if( b== '\r'){
                continue;
            }
            line.append((char) b);
        }
        return line.toString();
    }
}
